<script setup>
import { ref, onMounted } from "vue";
import "@material/web/list/list.js";
import "@material/web/list/list-item.js";

const START_YEAR = 1970;
const END_YEAR = 2100;
const YEAR_LENGTH = END_YEAR - START_YEAR + 1;

const props = defineProps(["year"]);
const emit = defineEmits(["change"]);
const yearList = ref(null);
const items = ref(null);

onMounted(() => {
  const year = props.year;
  if (year === undefined) {
    return;
  }

  setTimeout(() => {
    let top = 0;
    for (let i = 0; i < YEAR_LENGTH; i++) {
      if (i == year - START_YEAR) {
        top += items.value[i].offsetHeight / 2;
        break;
      } else {
        top += items.value[i].offsetHeight;
      }
    }
    top -= yearList.value.clientHeight / 2;
    yearList.value.scrollTo({
      top,
      left: 0,
      behavior: "instant"
    });
  }, 0);
});
</script>

<template>
  <md-list class="year-list" ref="yearList">
    <md-list-item v-for="i in YEAR_LENGTH" :key="i" type="button" @click="$emit('change', START_YEAR + i - 1)"
      ref="items">
      <div slot="start" class="start" role="presentation">
        <md-icon v-if="year == START_YEAR + i - 1">check</md-icon>
        <div class="placeholder" v-else></div>
      </div>
      <div slot="headline">
        {{ START_YEAR + i - 1 }}
      </div>
    </md-list-item>
  </md-list>
</template>

<style scoped>
.year-list {
  padding: 0;
  overflow-y: auto;
  height: 100%;
}

.start {
  display: flex;
  align-items: center;
}

.placeholder {
  display: inline-block;
  height: 24px;
  width: 24px;
}
</style>